using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Collections.Concurrent;

namespace WpfApp_ChenxiConsole.OTA
{
    /// <summary>
    /// ECU OTA升级配置类
    /// </summary>
    public class EcuOtaConfig : System.ComponentModel.INotifyPropertyChanged
    {
        private string _firmwareVersion = string.Empty;
        [JsonPropertyName("firmware_version")]
        public string FirmwareVersion 
        {
            get { return _firmwareVersion; }
            set 
            { 
                _firmwareVersion = value; 
                OnPropertyChanged(nameof(FirmwareVersion));
            }
        }

        private string _hardwareVersion = string.Empty;
        [JsonPropertyName("hardware_version")]
        public string HardwareVersion 
        {
            get { return _hardwareVersion; }
            set 
            { 
                _hardwareVersion = value; 
                OnPropertyChanged(nameof(HardwareVersion));
            }
        }

        private string _updateTime = string.Empty;
        [JsonPropertyName("update_time")]
        public string UpdateTime 
        {
            get { return _updateTime; }
            set 
            { 
                _updateTime = value; 
                OnPropertyChanged(nameof(UpdateTime));
            }
        }

        private string _filePath = string.Empty;
        [JsonPropertyName("file_path")]
        public string FilePath 
        {
            get { return _filePath; }
            set 
            { 
                _filePath = value; 
                OnPropertyChanged(nameof(FilePath));
            }
        }

        private string _crcChecksum = string.Empty;
        [JsonPropertyName("crc_checksum")]
        public string CrcChecksum 
        {
            get { return _crcChecksum; }
            set 
            { 
                _crcChecksum = value; 
                OnPropertyChanged(nameof(CrcChecksum));
            }
        }

        private string _description = string.Empty;
        [JsonPropertyName("description")]
        public string Description 
        {
            get { return _description; }
            set 
            { 
                _description = value; 
                OnPropertyChanged(nameof(Description));
            }
        }

        public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged;
        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
        }
    }

    /// <summary>
    /// ECU OTA管理器类，用于处理ECU的OTA升级功能
    /// </summary>
    public class EcuOtaManager
    {
        // 保存已加载的ECU OTA配置
        private EcuOtaConfig? _currentConfig = null;
        
        // 静态队列，用于存储从TCP消息过滤器接收的消息
        private static readonly ConcurrentQueue<string> _receivedMessagesQueue = new();
        
        /// <summary>
        /// 获取ECU升级窗口的接收队列
        /// </summary>
        public static ConcurrentQueue<string> ReceivedMessagesQueue => _receivedMessagesQueue;
        
        /// <summary>
        /// 向接收队列添加消息
        /// </summary>
        /// <param name="message">要添加的消息</param>
        public static void AddToReceivedQueue(string message)
        {
            _receivedMessagesQueue.Enqueue(message);
        }

        /// <summary>
        /// 获取当前加载的ECU OTA配置
        /// </summary>
        public EcuOtaConfig? CurrentConfig => _currentConfig;

        /// <summary>
        /// 加载ECU OTA配置JSON文件
        /// </summary>
        /// <param name="filePath">JSON文件路径</param>
        /// <returns>ECU OTA配置对象</returns>
        public EcuOtaConfig LoadEcuOtaConfig(string filePath)
        {
            try
            {
                if (!File.Exists(filePath))
                {
                    throw new FileNotFoundException("JSON配置文件不存在", filePath);
                }

                // 读取并解析JSON文件
                string jsonContent = File.ReadAllText(filePath);
                EcuOtaConfig? config = JsonSerializer.Deserialize<EcuOtaConfig>(jsonContent);
                if (config == null)
                {
                    throw new Exception("解析JSON配置文件得到空对象");
                }

                // 验证配置文件内容
                ValidateConfig(config, filePath);

                // 保存当前配置
                _currentConfig = config;

                return config!; // 使用null宽恕运算符，表示我们确信config不为null
            }
            catch (JsonException ex)
            {
                throw new Exception("解析JSON配置文件失败: " + ex.Message);
            }
            catch (Exception ex)
            {
                throw new Exception("加载ECU OTA配置文件失败: " + ex.Message);
            }
        }

        /// <summary>
        /// 验证ECU OTA配置
        /// </summary>
        /// <param name="config">ECU OTA配置对象</param>
        /// <param name="filePath">配置文件路径</param>
        private void ValidateConfig(EcuOtaConfig config, string filePath)
        {
            if (string.IsNullOrEmpty(config.FirmwareVersion))
            {
                throw new Exception("配置文件缺少固件版本信息");
            }

            if (string.IsNullOrEmpty(config.HardwareVersion))
            {
                throw new Exception("配置文件缺少硬件版本信息");
            }

            // 如果配置中指定了固件文件路径，验证该文件是否存在
            if (!string.IsNullOrEmpty(config.FilePath))
            {
                // 如果是相对路径，则相对于配置文件路径解析
                string firmwareFilePath = config.FilePath;
                if (!Path.IsPathRooted(firmwareFilePath))
                {
                    string? configDir = Path.GetDirectoryName(filePath);
                    if (configDir == null)
                    {
                        throw new Exception("无法解析配置文件的目录路径");
                    }
                    firmwareFilePath = Path.Combine(configDir!, firmwareFilePath); // 使用null宽恕运算符，表示我们确信configDir不为null
                }

                if (!File.Exists(firmwareFilePath))
                {
                    throw new Exception($"固件文件不存在: {firmwareFilePath}");
                }
            }
        }

        /// <summary>
        /// 执行ECU OTA升级准备工作
        /// </summary>
        /// <returns>准备结果</returns>
        public bool PrepareOtaUpgrade()
        {
            try
            {
                if (_currentConfig == null)
                {
                    throw new Exception("未加载ECU OTA配置文件");
                }

                // 此处可以添加升级前的准备工作，如检查设备连接、验证固件完整性等
                Console.WriteLine($"准备ECU OTA升级: 固件版本 {_currentConfig.FirmwareVersion}");
                Console.WriteLine($"硬件版本要求: {_currentConfig.HardwareVersion}");

                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine("ECU OTA升级准备失败: " + ex.Message);
                throw;
            }
        }

        /// <summary>
        /// 获取ECU OTA升级进度信息
        /// </summary>
        /// <returns>进度百分比</returns>
        public int GetUpgradeProgress()
        {
            // 这里只是一个示例实现，实际应该根据真实的升级进度返回
            // 在实际应用中，应该与底层通信获取真实的升级进度
            return 0;
        }

        /// <summary>
        /// 清除当前加载的ECU OTA配置
        /// </summary>
        public void ClearConfig()
        {
            _currentConfig = null;
        }
        
        /// <summary>
        /// 清除接收队列中的所有消息
        /// </summary>
        public static void ClearReceivedQueue()
        {
            while (!_receivedMessagesQueue.IsEmpty)
            {
                _receivedMessagesQueue.TryDequeue(out _);
            }
        }
    }
}